﻿using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Microsoft.SharePoint;

namespace Eneta.Portal.NewsAndBlogs.Controls
{
    public class NewsControl : UserControl
    {
        protected Repeater NewsWithSummary;
        protected Repeater BlogsWithSummary;
        protected Repeater NewsList;
        protected Repeater BlogList;
        private DataTable _news;
        private DataTable _blogs;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            var siteId = SPContext.Current.Site.ID;

            var sec = new SPSecurity.CodeToRunElevated(delegate
                       {
                           using (var site = new SPSite(siteId))
                           {
                               using (SPWeb blogsWeb = site.OpenWeb())
                               {
                                   using (SPWeb newsWeb = site.OpenWeb("/uudised/teated/"))
                                   {
                                       if (!IsPostBack)
                                       {
                                           GetNews(newsWeb,10);
                                           GetBlogs(blogsWeb,10);
                                       }
                                       if (_news != null)
                                       {
                                           if (_news.Rows.Count != 0)
                                           {
                                               NewsWithSummary.DataSource = FillResult(_news, 0,
                                                                                       2,
                                                                                       "/uudised/teated/");
                                               NewsWithSummary.DataBind();
                                               NewsList.DataSource = FillResult(_news, 2, 8,
                                                                                "/uudised/teated/");
                                               BlogList.DataBind();
                                           }
                                       }
                                       if (_blogs != null)
                                       {
                                           if (_blogs.Rows.Count != 0)
                                           {
                                               BlogsWithSummary.DataSource = FillResult(_blogs,
                                                                                        0, 2,
                                                                                        null);
                                               BlogsWithSummary.DataBind();
                                               BlogList.DataSource = FillResult(_blogs, 2, 8,
                                                                                null);
                                               BlogList.DataBind();
                                           }
                                       }
                                   }
                               }
                           }
                       });
            SPSecurity.RunWithElevatedPrivileges(sec);
        }

        private DataTable FillResult(DataTable source, int start, int end, string urlPrefix)
        {
            DataTable result = new DataTable();
            result.Columns.Add("Title", typeof(string));
            result.Columns.Add("Description", typeof(string));
            result.Columns.Add("URL", typeof(string));
            result.Columns.Add("Creator", typeof(string));
            result.Columns.Add("Created", typeof(string));
            result.Columns.Add("Source", typeof(string));
            result.Columns.Add("SourceUrl", typeof(string));
            DataRow resultRow;
            DataRow sourceRow;
            for (int i = start; i < end; i++)
            {
                if (source.Rows.Count <= i)
                    break;
                if (source.Rows[i] == null)
                    continue;
                resultRow = result.NewRow();
                sourceRow = source.Rows[i];
                if (sourceRow["Title"] != null)
                {
                    resultRow["Title"] = sourceRow["Title"];
                }
                else
                {
                    resultRow["Title"] = string.Empty;
                }
                if (sourceRow["Comments"] != null)
                {
                    resultRow["Description"] = sourceRow["Comments"];
                }
                else
                {
                    resultRow["Description"] = string.Empty;
                }
                if (sourceRow["FileLeafRef"] != null)
                {
                    if (urlPrefix != null)
                        resultRow["URL"] = urlPrefix + sourceRow["FileLeafRef"];
                    else
                        resultRow["URL"] = sourceRow["FileLeafRef"];
                }
                else
                {
                    resultRow["URL"] = string.Empty;
                }
                if (sourceRow["Author"] != null)
                {
                    resultRow["Creator"] = sourceRow["Author"];
                }
                else
                {
                    resultRow["Creator"] = string.Empty;
                }
                if (sourceRow["Created"] != null)
                {
                    DateTime date = DateTime.Parse(sourceRow["Created"].ToString());
                    resultRow["Created"] = date.ToShortDateString();
                }
                else
                {
                    resultRow["Created"] = string.Empty;
                }
                bool hasSource = source.Columns.Contains("Source");
                if (hasSource)
                {
                    if (sourceRow["Source"] != null)
                    {
                        resultRow["Source"] = sourceRow["Source"].ToString();
                    }
                    else
                    {
                        resultRow["Source"] = string.Empty;
                    }
                }
                bool hasSourceUrl = source.Columns.Contains("SourceUrl");
                if (hasSourceUrl)
                {
                    if (sourceRow["SourceUrl"] != null)
                    {
                        resultRow["SourceUrl"] = sourceRow["SourceUrl"].ToString();
                    }
                    else
                    {
                        resultRow["SourceUrl"] = string.Empty;
                    }
                }
                result.Rows.Add(resultRow);
            }
            return result;
        }

        private void GetNews(SPWeb web, uint resultCount)
        {
            var list = web.Lists["Lehed"];
            var items =
                Query.GetItems(list,
                               "<Where><Eq><FieldRef Name='ContentType'/><Value Type='Text'>Uudis</Value></Eq></Where><OrderBy><FieldRef Name='Created' Ascending='False'/></OrderBy>",
                               resultCount, new[] { "Title", "Comments", "Created", "Author" });
            if (items == null)
                return;
            if (items.Count == 0)
                return;
            _news = items.GetDataTable();
        }

        private void GetBlogs(SPWeb web, uint resultCount)
        {
            _blogs = new DataTable();
            _blogs.Columns.Add("Title", typeof(string));
            _blogs.Columns.Add("Comments", typeof(string));
            _blogs.Columns.Add("FileLeafRef", typeof(string));
            _blogs.Columns.Add("Author");
            _blogs.Columns.Add("Created");
            _blogs.Columns.Add("Source");
            _blogs.Columns.Add("SourceUrl");

            var list = web.Lists["FeedEntries"];
            
            SPListItemCollection items =
                Query.GetItems(list,
                               "<OrderBy><FieldRef Name='PublishDate' Ascending='False'/></OrderBy>", resultCount,
                               new string[] { "URL", "Title", "Summary", "Author", "PublishDate", "Feed" });
            if (items == null)
                return;
            DataRow row;
            foreach (SPListItem item in items)
            {
                row = _blogs.NewRow();
                if (item["Title"] != null)
                {
                    row["Title"] = item["Title"].ToString();
                }
                if (item["Summary"] != null)
                {
                    row["Comments"] = item["Summary"].ToString();
                }
                if (item["Author"] != null)
                {
                    SPFieldUserValue user = new SPFieldUserValue(web, item["Author"].ToString());
                    row["Author"] = user.LookupValue;
                }
                else
                {
                    row["Auhtor"] = string.Empty;
                }
                if (item["URL"] != null)
                {
                    row["FileLeafRef"] = "/uudised/Lehed/blogid.aspx?BlogId=" + item.ID;
                    //row["FileLeafRef"] = item["URL"].ToString();
                }
                else
                {
                    row["URL"] = string.Empty;
                }
                if (item["PublishDate"] != null)
                {
                    row["Created"] = DateTime.Parse(item["PublishDate"].ToString());
                }
                if (item["Feed"] != null)
                {
                    SPFieldLookupValue value = new SPFieldLookupValue(item["Feed"].ToString());
                    string[] source = GetBlogInfo(web, value.LookupId);
                    if (source != null)
                    {
                        if (source[0] != null)
                            row["Source"] = source[0];
                        else
                            row["Source"] = string.Empty;
                        if (source[1] != null)
                            row["SourceUrl"] = source[1];
                        else
                            row["SourceUrl"] = string.Empty;
                    }
                }
                else
                {
                    row["Source"] = string.Empty;
                    row["SourceUrl"] = string.Empty;
                }
                _blogs.Rows.Add(row);
            }
        }

        private string[] GetBlogInfo(SPWeb web, int id)
        {
            string[] result = new string[2];
            SPList list = web.Lists["Feeds"];
            if (list == null)
                return new string[2];
            SPListItemCollection items =
                Query.GetItems(list,
                    "<Where><Eq><FieldRef Name='ID'/><Value Type='Number'>" + id +
                    "</Value></Eq></Where>", 1, new string[] { "Link", "Title" });
            if (items == null)
                return new string[2];
            if (items[0]["Title"] != null)
                result[0] = items[0]["Title"].ToString();
            if (items[0]["Link"] != null)
            {
                SPFieldUrlValue value = new SPFieldUrlValue(items[0]["Link"].ToString());
                result[1] = value.Url;
            }
            return result;
        }
    }
}
